import random
from exit import db
from datetime import date, datetime, timedelta
from utils import restful, common_util
from apps.common.models import *
from apps.mall.models import *
from decimal import Decimal
from apps.api.models import User, UserRecord
from flask import g
import string
from sqlalchemy import func


def trade_time_required(trade_type):    # 时间管理

    trade_time = TradeManage.query.filter_by(trade_type=trade_type).first()
    if trade_time is None:
        return False
    if trade_time.trade_status == 1:
        return False
    start_time = datetime.strptime(str(datetime.now().date()) + str(trade_time.start_time), '%Y-%m-%d%H:%M:%S')
    end_time = datetime.strptime(str(datetime.now().date()) + str(trade_time.end_time), '%Y-%m-%d%H:%M:%S')
    now = datetime.now()
    if start_time > now or now > end_time:
        return False


def create_invite():    # 生成邀请码
    invite = ''
    for i in range(5):
        number = random.randint(0, 9)
        invite += str(number)
    user_invite = User.query.filter_by(invite=invite).first()
    if user_invite:
        invite = create_invite()
    else:
        return invite
    return invite


def record_type(r_label, r_type):   # 记录类型转换
    status = ''
    r_label = int(r_label)
    r_type = int(r_type)
    if r_label == 1:
        if r_type == 1:
            status = '交易竞拍买入'
        elif r_type == 3:
            status = '交易挂买'
        elif r_type == 4:
            status = '取消交易挂买'
        elif r_type == 7:
            status = '当日交易手续费总额'
        elif r_type == 8:
            status = '协议转入'
        elif r_type == 9:
            status = '冻结释放费'
        elif r_type == 10:
            status = '冻结转让费'
        elif r_type == 11:
            status = '撤消返还冻结转让费'
        elif r_type == 12:
            status = '当日冻结转让费总额'
        elif r_type == 13:
            status = '当日冻结释放费总额'
        # v2记录
        elif r_type == 20:
            status = '点对点买入'
        elif r_type == 21:
            status = '摘牌买入'
    elif r_label == 2:
        if r_type == 1:
            status = '拍卖居间费'
        elif r_type == 2:
            status = '预展居间费'
        elif r_type == 3:
            status = '取消拍卖'
        elif r_type == 5:
            status = '协议转入居间费'
        elif r_type == 6:
            status = '协议转出居间费'
        # v2记录
        elif r_type == 20:
            status = '点对点转出居间费'
        elif r_type == 21:
            status = '摘牌居间费'
        elif r_type == 22:
            status = '挂牌居间费'
    elif r_label == 3:
        if r_type == 1:
            status = '交易竞拍卖出'
        elif r_type == 2:
            status = '协议转出冻结票'
        # v2记录
        elif r_type == 20:
            status = '点对点转出'
        elif r_type == 21:
            status = '挂牌卖出'
    elif r_label == 6:
        if r_type == 1:
            status = '充值'
        elif r_type == 2:
            status = ''
    elif r_label == 7:
        if r_type == 1:
            status = '提现'
        elif r_type == 2:
            status = '取消提现'
    elif r_label == 10:
        if r_type == 1:
            status = '释放'
        elif r_type == 2:
            status = '系统转赠冻结'
        elif r_type == 3:
            status = '系统转赠释放'
        elif r_type == 4:
            status = '买入冻结票'
        elif r_type == 5:
            status = '转出冻结票'
        elif r_type == 6:
            status = '转赠冻结票'
        elif r_type == 7:
            status = '系统扣重原始冻结票'
        elif r_type == 8:
            status = '系统扣重赠送冻结票'
        elif r_type == 9:
            status = '系统扣重原始可用票'
        elif r_type == 10:
            status = '系统扣重赠送释放票'
        elif r_type == 11:
            status = '协议转出冻结票'
        elif r_type == 12:
            status = '协议转赠冻结票'
        elif r_type == 13:
            status = '协议转出可用票'
        elif r_type == 14:
            status = '协议转赠可用票'
        elif r_type == 15:
            status = '协议转出释放票'
        elif r_type == 16:
            status = '协议转赠释放票'
        elif r_type == 17:
            status = '协议买入冻结票'
        elif r_type == 18:
            status = '协议卖出冻结票'
        elif r_type == 19:
            status = '待释放票转可用票(锁定)'
        elif r_type == 20:
            status = '释放锁定票'
        elif r_type == 21:
            status = '待释放票转冻结票'
        elif r_type == 22:
            status = '锁定票转冻结票'

    elif r_label == 11:
        if r_type == 1:
            status = '系统扣重冻结余额'
        elif r_type == 2:
            status = '系统扣重提货保证金'
        elif r_type == 3:
            status = '协议转出余额'
        elif r_type == 4:
            status = '协议转赠余额'
        elif r_type == 5:
            status = '协议转出冻结余额'
        elif r_type == 6:
            status = '协议转赠冻结余额'
        elif r_type == 7:
            status = '协议转出提货保证金'
        elif r_type == 8:
            status = '协议转赠提货保证金'
    elif r_label == 15:
        if r_type\
                == 1:
            status = '点对点卖出'
        elif r_type == 2:
            status = '点对点买入'
        elif r_type == 3:
            status = ''
        elif r_type == 4:
            status = ''
    elif r_label == 16:
        if r_type == 1:
            status = ''
        elif r_type == 2:
            status = ''
        elif r_type == 3:
            status = ''
        elif r_type == 4:
            status = ''
    elif r_label == 20:  # 提货拍品
        if r_type == 1:
            status = '点对点收购'
        elif r_type == 2:
            status = '商城原价购买'
        elif r_type == 11:
            status = '提货'
    elif r_label == 21:  # 资产一
        if r_type == 1:
            status = '特价购买'
        elif r_type == 2:
            status = '撤销点对点'
        elif r_type == 11:
            status = '提货'
        elif r_type == 12:
            status = '点对点卖出'
    elif r_label == 22:  # 资产二
        if r_type == 1:
            status = '特价购买'
        elif r_type == 2:
            status = '优惠购买'
        elif r_type == 11:
            status = '提货'
        elif r_type == 12:
            status = '拍品释放'
    elif r_label == 23:  # 可交易拍品
        if r_type == 1:
            status = '拍品释放'
        elif r_type == 2:
            status = '商城购买'
        elif r_type == 3:
            status = '点对点购买'
        elif r_type == 4:
            status = '摘牌购买'
        elif r_type == 5:
            status = '挂牌撤销'
        elif r_type == 6:
            status = '点对点撤销'
        elif r_type == 11:
            status = '提货'
        elif r_type == 12:
            status = '点对点卖出'
        elif r_type == 13:
            status = '挂牌服务中心'
        elif r_type == 14:
            status = '挂牌供应商'

    elif r_label == 24:  # 特价券
        if r_type == 1:
            status = '提货赠送'
        elif r_type == 11:
            status = '过期'
        elif r_type == 12:
            status = '特价购买'

    elif r_label == 25:  # 优惠券
        if r_type == 1:
            status = '系统赠送'
        elif r_type == 2:
            status = '过期'
        elif r_type == 3:
            status = '特价购买'

    elif r_label == 101:
        if r_type == 1:
            status = ''
    elif r_label == 102:
        if r_type == 1:
            status = ''
    return status


def record_label(r_label):
    status = ''
    r_label = int(r_label)
    if r_label == 1:
        status = ''
    elif r_label == 2:
        status = ''
    elif r_label == 3:
        status = ''
    elif r_label == 4:
        status = '交易记录'
    elif r_label == 5:
        status = '转账记录'
    elif r_label == 6:
        status = ''
    elif r_label == 7:
        status = '提现'
    elif r_label == 8:
        status = '积分'
    return status


def user_record(user_id, r_label, r_type, r_state, r_wallet, num, other_id=None, status=0, r_coin=None, order_id=None):
    """
    添加记录
    :param user_id: 用户id
    :param r_label: 记录标签
    :param r_type: 记录类型
    :param num: 数量
    :param other_id: 对方id
    :param r_state: 1加2减
    :param r_wallet: 钱包
    :param status: 展示状态
    :param r_coin: 展示状态
    :param order_id: 订单ID
    :return:
    """
    record = UserRecord(user_id=user_id, r_label=r_label, r_type=r_type, num=num, r_state=r_state, other_id=other_id, r_wallet=r_wallet, status=status, r_coin=r_coin, order_id=order_id)
    db.session.add(record)


def level_str(user_level):
    to_str = ''
    if user_level == 1:
        to_str = ''
    elif user_level == 2:
        to_str = ''
    elif user_level == 3:
        to_str = ''
    elif user_level == 4:
        to_str = ''
    elif user_level == 5:
        to_str = ''
    elif user_level == 6:
        to_str = ''
    elif user_level == 7:
        to_str = ''
    elif user_level >= 8:
        to_str = ''
    return to_str


def pay_type_to_str(pay_type):  # 支付方式
    if pay_type == '1':
        pay_str = '现金支付'
    elif pay_type == '2':
        pay_str = '余额支付'
    else:
        pay_str = ''
    return pay_str


def order_status_to_str(status):  # 支付方式
    if status == 1:
        pay_str = '待发货'
    elif status == 2:
        pay_str = '待确认'
    elif status == 3:
        pay_str = '已完成'
    elif status == 4:
        pay_str = '失败'
    elif status == 5:
        pay_str = ''
    else:
        pay_str = ''
    return pay_str


def create_user_path(real_user, sub_user):  # 生成用户p_id  p_path  每个人只有两个直推 多了就往下排
    p_user = User.query.filter(
        User.p_path.like("%" + str(real_user.id) + "%"),
        User.direct_num < 2
    ).order_by(func.length(User.p_path), User.create_time).first()    # 查找需要安插的下级用户
    if p_user and real_user.direct_num >= 2:
        sub_user.p_id = p_user.id
        sub_user.rp_id = real_user.id
        p_user.team_num += 1
        p_user.direct_num += 1
        if p_user.p_path is None:
            sub_user.p_path = p_user.id
        else:
            sub_user.p_path = '{},{}'.format(p_user.id, p_user.p_path)
            p_path_list = p_user.p_path.split(',')
            for i in p_path_list:
                parent_user_1 = User.query.filter_by(id=i).first()
                parent_user_1.team_num += 1
    else:
        real_user.team_num += 1
        real_user.direct_num += 1
        sub_user.p_id = real_user.id
        sub_user.rp_id = real_user.id
        if real_user.p_path is None:
            sub_user.p_path = real_user.id
        else:
            sub_user.p_path = '{},{}'.format(real_user.id, real_user.p_path)
            p_path_list = real_user.p_path.split(',')
            for i in p_path_list:
                parent_user_1 = User.query.filter_by(id=i).first()
                parent_user_1.team_num += 1


def goods_category_json_list(category_id):
    goods_list = list()
    goods = Goods.query.filter(
        Goods.is_show == 0, Goods.category_id.like('%' + str(category_id) + '%')
    ).all()
    for i in goods:
        goods_info = i.goods_json()
        goods_list.append(goods_info)
    return goods_list


def order_goods_status_str(status):
    status_str = ''
    if status == 0:
        status_str = '购买'
    elif status == 1:
        status_str = '审核中'
    elif status == 2:
        status_str = '退款成功'
    elif status == 3:
        status_str = '驳回退款'
    return status_str


def order_goods_back_status_str(status):
    status_str = ''
    if status == 0:
        status_str = '未退换'
    elif status == 1:
        status_str = '只退款'
    elif status == 2:
        status_str = '退换货'
    elif status == 3:
        status_str = '退货退款'
    return status_str


def split_order(p_order, user):     # 根据店铺拆分订单
    buy_order_goods = BuyOrderGoods.query.filter_by(order_id=p_order.id, user_id=user.id).all()
    store_dict = dict()

    # 根据商品查看有归属几个店铺
    for i in buy_order_goods:
        if str(i.store_id) not in store_dict.keys():
            store_dict['{}'.format(i.store_id)] = list()
        store_dict['{}'.format(i.store_id)].append(i)

    # print(store_dict)
    # print(len(store_dict))
    if len(store_dict) < 2:
        store = GoodsStore.query.filter_by(id=p_order.store_id).with_for_update().first()
        store.income_s += p_order.actual_price
        # db.session.commit()
        return
    # goods_coupons = Coupons.query.filter_by(id=p_order.coupons_id).first()
    for store_id, goods_data in store_dict.items():
        # print(goods_data)
        store = GoodsStore.query.filter_by(id=store_id).first()
        trade_no = common_util.trade_no_time()
        buy_order = BuyOrder(user_id=user.id, trade_no=trade_no, status=1)
        db.session.add(buy_order)

        order_total_price = 0
        order_actual_price = 0
        order_total_num = 0
        order_total_freight = 0
        order_special_price = 0

        for j in goods_data:
            goods_id = j.goods_id
            num = int(j.goods_num)

            # 订单信息
            order_total_num += j.goods_num
            order_total_price += j.total_price
            order_total_freight += j.freight
            order_actual_price += j.actual_price

            goods = Goods.query.filter_by(id=goods_id).first()
            if goods.status == 1:
                order_special_price += (goods.price * num)

            # 生成新的订单对应的商品
            order_goods = BuyOrderGoods(
                user_id=user.id, order_id=buy_order.id,
                goods_id=goods.id, store_id=goods.store_id,
                goods_name=goods.name, goods_num=num, price=goods.price,
                total_price=j.total_price, freight=goods.freight,
                actual_price=j.actual_price, goods_status=goods.status,
                goods_code=goods.goods_code
            )
            db.session.add(order_goods)

        # 订单信息
        buy_order.pay_type = p_order.pay_type   # 购买类型
        buy_order.total_price = order_total_price   # 商品总价
        buy_order.special_price = order_special_price   # 特殊商品总价
        buy_order.actual_price = order_actual_price     # 实际支付价格
        buy_order.total_num = order_total_num           # 商品总数量
        buy_order.freight = order_total_freight         # 商品总运费
        buy_order.p_id = p_order.id                     # 父级id
        buy_order.address_id = p_order.address_id       # 父级地址id
        buy_order.store_id = store_id                   # 店铺地址id
        buy_order.user_status = p_order.user_status     # 用户购买状态
        buy_order.goods_status = store.status           # 订单商品状态
        # 店铺信息
        store.income_s += order_actual_price

    # 父级订单隐藏
    p_order.is_show = 1


def deal_record(buyer_id, seller_id, deal_price, deal_num, s_num, s_num_sell, t_type, deal_type=3, tn_day=0, goods_id='80', sell_batch_id=None, status=0):

    record = BuyDeal(buyer_id=buyer_id, seller_id=seller_id, deal_type=deal_type, deal_num=deal_num,
                     deal_price=deal_price, deal_money=deal_num*deal_price, s_num=s_num, s_num_sell=s_num_sell,
                     goods_id=goods_id, tn_day=tn_day, t_type=t_type, sell_batch_id=sell_batch_id, status=status)
    db.session.add(record)
